<script setup type="module" lang="ts">
import { onMounted, ref, computed, inject } from 'vue';
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist/build/pdf.mjs';
import HeaderDemo from '../components/HeaderDemo.vue';
import { ElMessage } from 'element-plus'; // 引入 ElMessage
// 引入图片
import collectIcon from '../img/collect.png';
import collectedIcon from '../img/uncollect.png';
import { useRoute, useRouter } from 'vue-router'
// 引入状态管理文件
import { useTokenStore } from '../stores/token'
import CryptoJS from 'crypto-js';
import { set } from 'jodit/types/core/helpers';


const axios = inject('axios') //注入 axios
// 创建路由对象，用于编程式导航
const router = useRouter()
const route = useRoute();
// 创建 Token 状态管理 Store
const userStore = useTokenStore()

// 获取登录的 Token
const token = ref(userStore.getToken())

//解密token
function getToken() {
    const encryptedToken = localStorage.getItem('token');
    if (encryptedToken) {
        const secretKey = 'your_secret_key'; // 使用相同的密钥
        const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
        const decryptedToken = bytes.toString(CryptoJS.enc.Utf8);
        return decryptedToken;
    }
    return null;
}
//初始化富文本
const richTextContent = ref('')
const bookTitle = ref('');  // 存储书名
const authorName = ref('');  // 存储作者名
const updateDate = ref('');  // 存储更新时间
const wordCount = ref(0);    //存储字数
const wid = ref(route.params.id as string);
 

//存储剧本信息
const getScriptInfo = async (id) => {
    try {



        // 发送请求获取剧本信息
        const response = await axios.get(`http://localhost:8080/api/getwork/` + id);

        // 将返回的数据赋值给对应的变量
        console.log('剧本信息:', response.data);
        // 去除 wddata 中的 HTML 标签，获取纯文本
        const textContent = response.data.wddata.replace(/<[^>]+>/g, '');
        richTextContent.value = response.data.wddata;  //wddata 是富文本数据
        bookTitle.value = response.data.wname;  // 设置书名
        authorName.value = response.data.uname;  // 设置作者名
        updateDate.value = response.data.wnowdate;  // 设置更新时间
        wordCount.value = textContent.length; // 计算字数
    } catch (error) {
        console.error('获取脚本信息时出错:', error);
    }
}




// 设置 pdf.js 的 worker 文件路径
GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).href;

const pdfCanvas = ref(null);
const pageNumber = ref(1); // 当前页数
let pdfDoc = null; // pdf 文档对象
const totalPages = ref(0); // 总页数
const isCollected = ref(false); // 收藏状态

// 新增：定义阅读模式状态
const isNightMode = ref(false);
// 切换阅读模式的函数
const toggleMode = () => {
    isNightMode.value = !isNightMode.value;
};




const collectURL = computed(() => {
    return isCollected.value ? collectedIcon : collectIcon;
});

// 切换收藏状态
const toggleCollect = () => {
    isCollected.value = !isCollected.value;
};

const renderPage = async (num) => {
    const page = await pdfDoc.getPage(num);
    const scale = 1.6; // Adjust scale as needed
    const viewport = page.getViewport({ scale });

    // Create a new canvas element for each page
    const canvas = document.createElement('canvas');
    canvas.width = viewport.width;
    canvas.height = viewport.height;

    const context = canvas.getContext('2d');

    const renderContext = {
        canvasContext: context,
        viewport,
    };

    await page.render(renderContext).promise; // 渲染页面

    // Append the rendered canvas to the pdf-container element
    const pdfContainer = document.querySelector('.pdf-container');
    pdfContainer.appendChild(canvas); // 将每个 canvas 添加到 pdfContainer

    console.log(`Page ${num} rendered successfully`);
};

const setmode = (mode) => {

};


// 跳转到指定页数的函数
const goToPage = (page) => {
    if (page >= 1 && page <= totalPages.value) {
        pageNumber.value = page;
        renderPDF(); // 重新渲染 PDF
    }
    renderPage(pageNumber.value); // 渲染指定页面
};
const prevPage = () => {
    if (pageNumber.value > 1) {
        goToPage(pageNumber.value - 1);
    }
};

const nextPage = () => {
    if (pageNumber.value < totalPages.value) {
        goToPage(pageNumber.value + 1);
    }
};
const renderPDF = () => {
    // 这里调用你原有的 PDF 渲染逻辑
    console.log(`Render page: ${pageNumber.value}`);
    renderPage;
    // 例如 context.drawImage(...);
};


onMounted(async () => {
    // 获取路径下的 id
    const wid = route.params.id as string;
    console.log('路由参数:', wid);
    await getScriptInfo(wid);
    const Token = getToken();
    if (Token) {
        const currentUrl = window.location.href;
        const lastPart = currentUrl.split('/').pop();

        const loadingTask = fetch('http://localhost:8080/api/view-pdf', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${Token}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ wid: lastPart }),
        });

        try {
            const response = await loadingTask;
            if (!response.ok) {
                ElMessage.error('登录过期，请重新登录！');
                router.push('/login');
                throw new Error('网络响应不正常');
            }
            console.log('Response:', response);

            const pdfBlob = await response.blob();
            const pdfUrl = URL.createObjectURL(pdfBlob);
            pdfDoc = await getDocument(pdfUrl).promise;
            totalPages.value = pdfDoc.numPages;

            // 循环渲染所有页面
            for (let pageNum = 1; pageNum <= totalPages.value; pageNum++) {
                await renderPage(pageNum);
            }
        } catch (error) {
            console.error('Error rendering PDF:', error);
        }

    } else {
        ElMessage.error('登录过期，请重新登录！');
        router.push('/login');
    }


});
</script>

<template>
    <div class="main" :class="{ 'night-mode': isNightMode }">
        <div class="container">
            <div class="text-container">
                <!-- 头部信息区域 -->
                <div class="header-info">
                    <h1 class="book-title">{{ bookTitle }}</h1>
                    <p class="book-meta">
                        作者名：{{ authorName }}　本章字数：{{ wordCount }}字　更新时间：{{ updateDate }}
                        
                    </p>
                    <hr class="divider">
                </div>
                <div v-html="richTextContent" class="rich-text-content"></div>
            </div>

            <!-- Right side menu -->
            <div class="side-menu">
                <div class="menu-item">
                    <img src="@/img/menu-icon1.png" alt="目录" class="menu-icon">
                    <span>目录</span>
                </div>
                <div class="menu-item " @click="router.push('/workprofile/'+wid)"> 
                    <img src="@/img/menu-icon2.png" alt="书详情" class="menu-icon" >
                    <span>书详情</span>
                </div>

                <div class="menu-item" @click="toggleMode">
                    <img src="@/img/menu-icon5.png" alt="夜间" class="menu-icon">
                    <span>{{ isNightMode ? '取消夜间模式' : '夜间模式' }}</span>
                </div>
                <div class="menu-item">
                    <img src="@/img/menu-icon6.png" alt="设置" class="menu-icon">
                    <span>设置</span>
                </div>

                <div class="menu-item">
                    <img src="@/img/menu-icon8.png" alt="向上" class="menu-icon">
                    <span>向上</span>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
/* .header {
    background-image: url("../../public/images/mantianfanxing.jpg");
    height: 80px;
    margin: 0;
} */
.main {
    min-height: 100%;
    margin: 0 5px;
    /* 左右外边距 5px */
    border-radius: 1px;
    /* 设置圆角，1px 可以根据需要调整 */
    background-color: rgb(235, 228, 219);
}

.night-mode {
    background-color: #121212; /* 夜间模式背景色 */
    color: white; /* 夜间模式文字颜色 */
}

.night-mode .book-title,
.night-mode .book-meta {
    color: white; /* 夜间模式标题和元数据颜色 */
}

.night-mode .divider {
    border-top: 1px dashed #444; /* 夜间模式下分割线颜色 */
}

.night-mode .rich-text-content {
    color: #e0e0e0; /* 夜间模式富文本颜色 */
}
.night-mode .text-container {
    flex: 1;
    /* 让文本容器扩展占满剩余空间 */
    max-width: 800px;
    /* 设置最大宽度 */
    background-color: #040b39;
    /* 浅米色背景 */
    padding: 20px;
    border: 1px solid #dcdcdc;
    /* 边框 */
    margin-right: 10px;
    /* 与侧边菜单保持一些间距 */
    margin-left: auto;
    /* 使文本容器从左边自动对齐 */

    font-family: 'Georgia', serif;
    /* 使用 serif 字体 */
}

.container {
    min-height: 100vh;
    display: flex;
    /* 设置为 Flexbox */
    justify-content: center;
    /* 水平居中内容 */
    align-items: flex-start;
    /* 垂直居中内容 */
    /* background-color: rgb(235, 228, 219); */
}

.header-info {
    text-align: center;
    margin-bottom: 15px;
}

.book-title {
    font-size: 24px;
    font-weight: bold;
    margin: 0;
    color: #333;
}

.book-meta {
    font-size: 14px;
    color: #666;
    margin-top: 5px;
    margin-bottom: 10px;
}

.divider {
    border: none;
    border-top: 1px dashed #ccc;
    margin: 10px 0;
}


.text-container {
    flex: 1;
    /* 让文本容器扩展占满剩余空间 */
    max-width: 800px;
    /* 设置最大宽度 */
    background-color: #f8f4e5;
    /* 浅米色背景 */
    padding: 20px;
    border: 1px solid #dcdcdc;
    /* 边框 */
    margin-right: 10px;
    /* 与侧边菜单保持一些间距 */
    margin-left: auto;
    /* 使文本容器从左边自动对齐 */

    font-family: 'Georgia', serif;
    /* 使用 serif 字体 */
}



.rich-text-content {
    min-height: 10%;
    font-family: 'Times New Roman', Times, serif;
    font-size: 18px;
    line-height: 1.6;
    color: #333;
    /* Dark grey for readability */
}

/* Right side menu */
/* Right side menu */
/* Right side menu */
/* Right side menu */
.side-menu {
    width: 80px;
    /* 固定宽度 */
    background-color: rgb(235, 228, 219);
    padding: 10px;
    border-radius: 8px;
    position: sticky;
    /* 随滚动条固定位置 */
    top: 20px;
    /* 与顶部保持一定距离 */
    margin-right: auto;
    /* 使文本容器从右边自动对齐 */
}

.menu-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #f0f0f0;
    width: 60px;
    padding: 10px 0;
    margin: 5px 0;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.3s;
}

.menu-item:hover {
    /* background-color: #e0ddd7; */
    border-color: #b7b7b7;
    /* 悬停时边框颜色 */
    border-style: solid;
    /* 悬停时边框宽度 */
    border-width: 1px;
}


.menu-icon {
    width: 24px;
    height: 24px;
    margin-bottom: 5px;
}

.menu-item span {
    font-size: 12px;
    color: #333;
}

/* //以下为设置富文本的样式 */
/* .ql-align-center{
    background-color: #9bde14;
} */

.rich-text-content>>>html,
.rich-text-content>>>body,
.rich-text-content>>>div,
.rich-text-content>>>ul,
.rich-text-content>>>li,
.rich-text-content>>>h1,
.rich-text-content>>>h2,
.rich-text-content>>>h3,
.rich-text-content>>>h4,
.rich-text-content>>>h5,
.rich-text-content>>>h6,
.rich-text-content>>>p,
.rich-text-content>>>ol,
.rich-text-content>>>pre {
    margin: 0;
    padding: 0;
    margin-bottom: 30px;
    font-weight: normal;
}

.rich-text-content>>>p {
    /* 设置行间距 */
    line-height: 30px;
}

u {
    text-decoration: underline;
    /*下划线*/
}

s {
    text-decoration: line-through;
    /*删除线*/
}

.rich-text-content>>>p {
    white-space: pre-wrap;
    /*保留换行符*/
    word-wrap: break-word;
    /*自动换行*/
}

.rich-text-content>>>body {
    padding: 20px;
}

.rich-text-content>>>strong {
    font-weight: bold;
}

.rich-text-content>>>.ql-align-center {
    text-align: center;
}

.ql-align-right {
    text-align: right;
}

.rich-text-content>>>.ql-align-justify {
    text-align: justify !important;
    /*文本两端对齐*/
}

.rich-text-content>>>.ql-align-justify em {
    text-align: justify !important;
    background-color: #9bde14;
    /*文本两端对齐*/
}

h1 {
    margin-bottom: 20px;
}

h2 {
    margin-bottom: 10px;
}
</style>
